package cn.walls1717.juc.tl;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * ThreadLocal基本用法测试
 *
 * @author walls1717
 * @create 2022/12/14 14:33
 **/
@Slf4j
public class ThreadLocalDemo {

    public static void main(String[] args) throws InterruptedException {
        House house = new House();
        for (int i = 1; i <= 5 ; i++) {
            new Thread(()->{
                int size = new Random().nextInt(5) + 1;
                // log.info("卖出 " + size);
                try {
                    for (int j = 1; j <= size ; j++) {
                        house.saleHouse();
                        house.saleByThreadLocal();
                    }
                    log.info(Thread.currentThread().getName() + "号卖出 " + house.saleV.get());
                } finally {
                    house.saleV.remove();
                }
            }).start();
        }

        TimeUnit.MILLISECONDS.sleep(300);

        log.info("共计卖出 " + house.saleCount);
    }
}

class House {
    int saleCount = 0;

    ThreadLocal<Integer> saleV = ThreadLocal.withInitial(() -> 0);

    public synchronized void saleHouse() {
        ++saleCount;
    }

    public void saleByThreadLocal() {
        saleV.set(1 + saleV.get());
    }
}
